﻿#region License
// (c) Intergen.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using MediaWiki.Common;
using MediaWiki.Office.Model.Utilities;

namespace MediaWiki.Office.Model
{
  public class NumberingDefinition
  {
    private readonly DelegateKeyedCollection<int, NumberingLevel> _numberingLevels =
      new DelegateKeyedCollection<int, NumberingLevel>(i => i.Level);

    private Document _document;
    private int _numberId;

    public Document Document
    {
      get { return _document; }
      set { _document = value; }
    }

    public int NumberId
    {
      get { return _numberId; }
      set { _numberId = value; }
    }

    public DelegateKeyedCollection<int, NumberingLevel> NumberingLevels
    {
      get { return _numberingLevels; }
    }

    public NumberingDefinition(Document document, XElement numberDefinitionElement, XElement abstractDefinitionElement)
    {
      if (document == null)
        throw new ArgumentNullException("document");
      if (numberDefinitionElement == null)
        throw new ArgumentNullException("numberDefinitionElement");
      if (abstractDefinitionElement == null)
        throw new ArgumentNullException("abstractDefinitionElement");

      _document = document;

      XNamespace ns = Document.WordprocessingML;

      _numberId = (int)numberDefinitionElement.Attribute(ns + "numId");

      var overrides = from e in numberDefinitionElement.Elements(ns + "lvlOverride").Elements(ns + "lvl")
                      select new NumberingLevel(this, e);

      //  throw new Exception("Level override supplied.");

      var levels = from e in abstractDefinitionElement.Elements(ns + "lvl")
                   let lvlId = (int)e.Attribute(ns + "ilvl")
                   where overrides.Where(nl => nl.Level == lvlId).Count() == 0
                   select new NumberingLevel(this, e);

      List<NumberingLevel> result = levels.Union(overrides).ToList();

      _numberingLevels.AddRange(result);
    }
  }
}